﻿using Mangdot.Webchat.Common;
using Mangdot.Webchat.Models;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace Mangdot.Webchat.Controllers
{
    public class WeChatController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AuthorizeCallback()
        {
            string code = Request["code"];
            string state = Request["state"];

            if (string.IsNullOrEmpty(code))
            {
                Logger.Trace("获取code失败");
            }

            Logger.Trace("code=" + code);

            var openId = WebchatService.GetUserInfo(code);
            Session["UserId"] = openId;

            return RedirectToAction("Index", "Home");
        }

        public string CallBack()
        {
            if (Request.HttpMethod.ToUpper() == "GET")
            {
                string signature = Request.QueryString["signature"]; //微信加密签名
                string timestamp = Request.QueryString["timestamp"];//时间戳
                string nonce = Request.QueryString["nonce"];//随机数
                string echostr = Request.QueryString["echostr"];   //随机字符串

                string token = "Mangdot";   //配置时写的token
                string[] ArrTmp = { token, timestamp, nonce };
                Array.Sort(ArrTmp);
                string tmpStr = string.Join("", ArrTmp);

                var result = Common.Security.EncryptToSHA1(tmpStr).ToLower();

                //var response = new HttpResponseMessage()
                //{
                //    Content = new StringContent(echostr, Encoding.GetEncoding("UTF-8"), "application/x-www-form-urlencoded")
                //};

                //return response;
                return echostr;
            }
            string responseContent = "";
            if (Request.HttpMethod.ToUpper() == "POST")
            {
                string postString = string.Empty;

                using (Stream stream = Request.InputStream)
                {
                    Byte[] postBytes = new Byte[stream.Length];
                    stream.Read(postBytes, 0, (Int32)stream.Length);

                    postString = Encoding.GetEncoding("UTF-8").GetString(postBytes);
                    Logger.Trace("接收数据：" + postString);
                    string nadme = HttpUtility.UrlDecode(postString);//加上这句话的目的为了本地调试
                    nadme = nadme.Replace("=", "");//加上这句话的目的为了本地调试
                    responseContent = this.ReturnMessage(nadme);
                    //返回的消息为UTF-8格式		

                }
                //var responses = new HttpResponseMessage()
                //{
                //    Content = new StringContent(responseContent, Encoding.GetEncoding("UTF-8"), "text/xml")
                //};
                return responseContent;
            }
            return null;
        }

        /// <summary>
        /// 验证登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return Redirect(WebchatService.GetCode());
        }


        /// <summary>
        /// JSSDK 初始化获取各个参数
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetSDKConfig(string url)
        {
            //string url = Request.Url.AbsoluteUri;
            var data = WebchatService.GetWXConfig(url);
            return Json(data);
        }

        /// <summary>
		/// 统一全局返回消息处理方法
		/// </summary>
		/// <param name="postStr"></param>
		/// <returns></returns>
		public string ReturnMessage(string postStr)
        {
            string responseContent = "";
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(postStr);
            XmlNode MsgType = xmldoc.SelectSingleNode("/xml/MsgType");
            Logger.Info("消息类型:" + MsgType.InnerText);
            if (MsgType != null)
            {
                switch (MsgType.InnerText)
                {
                    case "event":
                        responseContent = EventHandle(xmldoc);//菜单事件处理
                        break;
                    case "text":
                        responseContent = TextHandle(xmldoc);//文本消息处理
                        break;
                    case "image":
                        responseContent = ImageHandle(xmldoc);//文本消息处理
                        break;
                    case "voice":
                        responseContent = VoiceHandle(xmldoc);//文本消息处理
                        break;
                    default:
                        break;
                }
            }
            return responseContent;
        }

        /// <summary>
		/// 接收文本消息并回复自定义消息
		/// </summary>
		/// <param name="xmldoc"></param>
		/// <returns></returns>
		public string TextHandle(XmlDocument xmldoc)
        {
            string responseContent = "";
            string customeMsg = "";
            XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode CreateTime = xmldoc.SelectSingleNode("/xml/CreateTime");
            XmlNode MsgType = xmldoc.SelectSingleNode("/xml/MsgType");
            XmlNode Content = xmldoc.SelectSingleNode("/xml/Content");
            XmlNode MsgId = xmldoc.SelectSingleNode("/xml/MsgId");

            if (Content != null)
            {
                if (Content.InnerText == "never")
                {
                    customeMsg = "NeverLostHope";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[" + MsgType.InnerText + "]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";

                    responseContent = xmlMes;
                }
                else
                {
                    customeMsg = "您好，欢迎关注忙点贺卡<a href='http://wx.mangdot.com/html/index.html'>点击进入-></a>";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[" + MsgType.InnerText + "]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
                Logger.Info("TextHandle:" + responseContent);
            }
            return responseContent;
        }


        /// <summary>
        /// 接收图文消息并回复自定义消息
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <returns></returns>
        public string ImageHandle(XmlDocument xmldoc)
        {
            string responseContent = "";
            XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode CreateTime = xmldoc.SelectSingleNode("/xml/CreateTime");
            XmlNode MsgType = xmldoc.SelectSingleNode("/xml/MsgType");
            XmlNode PicUrl = xmldoc.SelectSingleNode("/xml/PicUrl");
            XmlNode MediaId = xmldoc.SelectSingleNode("/xml/MediaId");
            XmlNode MsgId = xmldoc.SelectSingleNode("/xml/MsgId");

            if (MediaId != null)
            {
                string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[" + MsgType.InnerText + "]]></MsgType><Image><MediaId><![CDATA[" + MediaId.InnerText + "]]></MediaId></Image></xml>";
                Logger.Info("ImageHandle:" + xmlMes);
                responseContent = xmlMes;
            }
            return responseContent;
        }

        /// <summary>
        /// 接收语音消息并回复自定义消息
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <returns></returns>
        public string VoiceHandle(XmlDocument xmldoc)
        {
            string responseContent = "";
            XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode CreateTime = xmldoc.SelectSingleNode("/xml/CreateTime");
            XmlNode MsgType = xmldoc.SelectSingleNode("/xml/MsgType");
            XmlNode Format = xmldoc.SelectSingleNode("/xml/Format");
            XmlNode MediaId = xmldoc.SelectSingleNode("/xml/MediaId");
            XmlNode MsgId = xmldoc.SelectSingleNode("/xml/MsgId");
            XmlNode Recognition = xmldoc.SelectSingleNode("/xml/Recognition");
            if (MediaId != null)
            {
                string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[" + MsgType.InnerText + "]]></MsgType><Voice><MediaId><![CDATA[" + MediaId.InnerText + "]]></MediaId></Voice></xml>";
                Logger.Info("VoiceHandle:" + xmlMes);
                responseContent = xmlMes;
            }
            return responseContent;
        }

        /// <summary>
        /// 菜单点击事件
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <returns></returns>
        public string EventHandle(XmlDocument xmldoc)
        {
            string responseContent = "";
            string customeMsg = "";
            XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode CreateTime = xmldoc.SelectSingleNode("/xml/CreateTime");
            XmlNode MsgType = xmldoc.SelectSingleNode("/xml/MsgType");
            XmlNode Event = xmldoc.SelectSingleNode("/xml/Event");
            XmlNode EventKey = xmldoc.SelectSingleNode("/xml/EventKey");

            Logger.Info("CLICK:" + EventKey.InnerText);
            if (EventKey != null)
            {
                if (EventKey.InnerText == "IOT")
                {
                    customeMsg = "物联网解决方案";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
                else if (EventKey.InnerText == "WebDev")
                {
                    customeMsg = "联系电话：18301432864";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
                else if (EventKey.InnerText == "Contact")
                {
                    customeMsg = "联系电话：18301432864";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
                else if (EventKey.InnerText == "DevHK")
                {
                    customeMsg = "正在开发中";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
                else
                {
                    customeMsg = "您好，欢迎关注忙点贺卡<a href='http://wx.mangdot.com/html/index.html'>点击进入-></a>";
                    string xmlMes = "<xml><ToUserName><![CDATA[" + FromUserName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.InnerText + "]]></FromUserName><CreateTime>" + CreateTime.InnerText + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + customeMsg + "]]></Content></xml>";
                    responseContent = xmlMes;
                }
            }
            return responseContent;
        }
    }
}